package drds.data_propagate.parse.ha;

import drds.data_propagate.common.AbstractLifeCycle;
import drds.data_propagate.parse.HaSwitchable;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 基于HeartBeat信息的HA控制 , 注意：非线程安全，需要做做多例化
 */
public class HeartBeatHaController extends AbstractLifeCycle implements HaController, HeartBeatCallback {

    private static final Logger logger = LoggerFactory.getLogger(HeartBeatHaController.class);
    // default 3 times
    @Setter
    @Getter
    private int detectingRetryTimes = 3;
    @Setter
    @Getter
    private int failedTimes = 0;
    @Setter
    @Getter
    private boolean switchEnable = false;
    @Setter
    @Getter
    private HaSwitchable haSwitchable;

    public HeartBeatHaController() {

    }

    public void onSuccess(long costTime) {
        failedTimes = 0;
    }

    public void onFailed(Throwable e) {
        failedTimes++;
        // 检查一下是否超过失败次数
        synchronized (this) {
            if (failedTimes > detectingRetryTimes) {
                if (switchEnable) {
                    haSwitchable.doSwitch();// 通知执行一次切换
                    failedTimes = 0;
                } else {
                    logger.warn("HeartBeat failed Times:{} , should auto switch ?", failedTimes);
                }
            }
        }
    }


}
